﻿///***************************************************************
/// 시  스  템 : Updms.Mny
/// 단위시스템 : MNY
/// 계      층 : Presentation Layer
/// 프로그램명 : Mny3012p
/// 파  일  명 : Mny3012p.aspx.cs
/// 설      명 : 생활비 차감관리
///***************************************************************
/// 수정ID 일자       이름     내용
///---------------------------------------------------------------
/// CH001  2010-06-08 송시명   최초 작성
///***************************************************************
using System;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;

using SMFramework.Data;
using SMFramework.Utility;

using Base.AppFramework.Web.UI.CommandBar;
using Base.Dac;
using Updms.Mny.Exe;


namespace Updms.Mny
{
	public partial class Mny3012p : Updms.Common.BaseClass.PageBase
	{
		#region 전역영역

		//프로그램상수
		public static readonly string PID = "Mny3012p";
		public static readonly string gs_path_info = "/updms/Mny/" + PID + ".aspx";

		Global global = new Global();

		//검색
		protected string kw1 = "";	//Seq

		//페이지별합계
		decimal ld_amount = 0;

		#endregion

		#region Page_Load, OnPageLoad

		protected void Page_Load(object sender, EventArgs e)
		{
			SetInit();
			if (!Page.IsPostBack)
			{
				// 최초 화면 로딩시 처리해야 할 부분
				OnPageLoad();
				SetLivingCost();
				SearchProcess();
			}
		}

		//OnPageLoad
		private void OnPageLoad()
		{
			SetLiterals(global.GetLabelInfoByPgmId(PID, LANG_SET));
			SetSearchParameter();
		}

		#endregion

		#region InitializeComponent

		private void InitializeComponent()
		{
			this.Load += new System.EventHandler(this.Page_Load);
			this.PreRender += new System.EventHandler(this.Page_PreRender);
		}

		#endregion

		#region SetInit, SetSearchParameter

		//초기값설정
		private void SetInit()
		{
		}

		//검색파라미터
		private void SetSearchParameter()
		{
			kw1 = string.IsNullOrEmpty(Request.QueryString["seqs"]) ? "" : Request.QueryString["seqs"].ToString();
		}

		#endregion

		#region 디테일 Method (SetLivingCost)

		//생활비계정
		private void SetLivingCost()
		{
			DataSet lo_ds = new DataSet();
			Mny3012p_NT _Mny3012p_NT = new Mny3012p_NT();

			lo_ds.Merge(_Mny3012p_NT.GetLivingCostForBalance());

			ddl_living_cost.Items.Clear();
			ddl_living_cost.DataSource = lo_ds;
			ddl_living_cost.DataMember = "UPDMS_MNY_IN_OUT_MGT";
			ddl_living_cost.DataTextField = "Text";
			ddl_living_cost.DataValueField = "Value";
			ddl_living_cost.DataBind();
		}

		#endregion

		#region CRUD (SelectProcess, UpdateProcess, SearchProcess)

		//조회
		private void SelectProcess()
		{
			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();

			//검색
			lo_dp.AddProperty("ls_seq", typeof(string), kw1);
			lo_dp.AddProperty("ls_lang_set", typeof(string), LANG_SET);

			using (Mny3012p_NT _Mny3012p_NT = new Mny3012p_NT())
			{
				lo_ds.Merge(_Mny3012p_NT.GetBalanceAmountList(lo_dp));

				bool lb_rslt = DataSetUtil.CheckRowCount(lo_ds, "UPDMS_MNY_IN_OUT_MGT");
				ibtn_save.Visible = lb_rslt;
				
				if (!lb_rslt)
				{
					//지출계정만 차감할 수 있습니다.(생활비 제외)
					CallMsgBoxInAjax("MSG_ERR_151");
				}

				GridView1.DataSource = lo_ds;
				GridView1.DataBind();
			}
		}

		//차감
		private void UpdateProcess()
		{
			DataPack lo_dp = new DataPack();
			lo_dp = SetValue();
			
			if (lo_dp.Keys.Count > 0)
			{
				using (Mny3012p_RT _Mny3012p_RT = new Mny3012p_RT())
				{
					int li_return = _Mny3012p_RT.SetLivingCostForBalance(SetValue());
					string ls_msg_id = (li_return > 0) ? "MSG_INF_015" : "MSG_ERR_147";	//차감되었습니다:차감할 수 없습니다
					CallMsgBoxInAjax(ls_msg_id);

					SearchProcess();
				}
			}
			else
			{
				CallMsgBoxInAjax("MSG_ERR_148");	//합계금액은 차감할 생활비의 금액보다 클 수 없습니다
			}
		}

		//검색
		private void SearchProcess()
		{
			SetSearchParameter();
			SelectProcess();
		}

		#endregion

		#region SetValue

		//SetValue
		private DataPack SetValue()
		{
			DataPack lo_dp = new DataPack();
			
			string ls_remark = "";
						
			//[2010-01-01] 생활비 [50,000]
			string ls_living_cost = ddl_living_cost.SelectedItem.Text;
			string ls_living_cost_split
				= ls_living_cost.Substring(ls_living_cost.LastIndexOf("[") + 1, ls_living_cost.Length - ls_living_cost.LastIndexOf("[") - 2);

			//GridView1의 합계금액
			int li_amount = Convert.ToInt32(ConversionUtil.RemoveComma(GridView1.FooterRow.Cells[6].Text));
			
			//ddl_living_cost의 금액에서 GridView1의 합계금액을 뺀다.
			int li_calc_amount = Convert.ToInt32(ConversionUtil.RemoveComma(ls_living_cost_split)) - li_amount;

			//Total금액은 차감할 생활비의 금액보다 클 수 없다.
			if (li_calc_amount > 0)
			{
				//Remark : 원래금액 - 차감한 내역
				for (int i = 0; i < GridView1.Rows.Count; i++)
				{
					CheckBox cb_check = (CheckBox)GridView1.Rows[i].Cells[0].FindControl("cb_check");

					if (cb_check.Checked)
					{
						ls_remark += " - " + GridView1.Rows[i].Cells[5].Text + "(" + GridView1.Rows[i].Cells[3].Text + ")";
					}
				}

				lo_dp.AddProperty("li_seq", typeof(int), ddl_living_cost.SelectedValue);
				lo_dp.AddProperty("li_amount", typeof(int), li_calc_amount);
				lo_dp.AddProperty("ls_remark", typeof(int), ls_living_cost_split + ls_remark);
				lo_dp.AddProperty("ls_user_id", typeof(int), USER_ID);
			}
						
			return lo_dp;
		}

		#endregion

		#region Page_PreRender, ChangePageMode

		// Page_PreRender
		private void Page_PreRender(object sender, System.EventArgs e)
		{
			if (!Page.IsPostBack)
			{
				using (AccessCheck access = new AccessCheck())
				{
					//접근권한 체크
					if (!access.CheckPgmAccessGrant(PID, USER_ID, ACCESS_LOG_INFO))
					{
						Response.Redirect(URL_NO_AUTHORITY_REDIRECT_POPUP);	//사용자의 권한은 요청하신 페이지를 볼 수 없습니다
					}
					//사용권한별 버튼처리
					PagePreRender.SetVisibleCtrl(this, access.CheckPgmUsingGrant(USER_DIV, PID), access.GetVisibleCtrl(PID));
				}
			}
			ChangePageMode();
		}

		//ChangePageMode
		private void ChangePageMode()
		{
			SetGridViewHeader(global.GetColumnListByPgmId(PID, LANG_SET));
		}

		#endregion

		#region GridView이벤트

		//RowDataBound
		protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
		{
			if (e.Row.RowType == DataControlRowType.DataRow)
			{
				//마우스올렸을 때
				e.Row.Attributes.Add("onmouseover", GRID_ONMOUSEOVER_COLOR);
				e.Row.Attributes.Add("onmouseout", GRID_ONMOUSEOUT_COLOR);

				//번호
				e.Row.Cells[1].Text = (e.Row.RowIndex + 1).ToString();
				
				//체크된 항목 합계
				CheckBox cb_check = (CheckBox)e.Row.Cells[0].FindControl("cb_check");

				if (cb_check.Checked)
				{
					ld_amount += Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "Amount"));
				}
			}

			//Footer에 합계 바인딩
			if (e.Row.RowType == DataControlRowType.Footer)
			{
				e.Row.Cells[0].Text = "Total";
				e.Row.Cells[0].Attributes.Add("class", "total");
				e.Row.Cells[0].ColumnSpan = 5;
				e.Row.Cells[1].Visible = false;
				e.Row.Cells[2].Visible = false;
				e.Row.Cells[3].Visible = false;
				e.Row.Cells[4].Visible = false;
				e.Row.Cells[5].Visible = false;
				e.Row.Cells[6].Text = ld_amount.ToString("#,###,##0");
				e.Row.Cells[6].Attributes.Add("class", "money");
				e.Row.Cells[7].Text = "";
				e.Row.Cells[7].Attributes.Add("class", "none");
			}
		}

		#endregion

		#region 버튼이벤트

		//저장
		protected void ibtn_save_Click(object sender, EventArgs e)
		{
			UpdateProcess();
		}

		//체크박스 클릭시 합계 재계산
		protected void cb_check_CheckedChanged(object sender, EventArgs e)
		{
			decimal ld_calc_amount = 0;
			
			//체크된 항목 합계
			for (int i = 0; i < GridView1.Rows.Count; i++)
			{
				CheckBox cb_check = (CheckBox)GridView1.Rows[i].Cells[0].FindControl("cb_check");

				if (cb_check.Checked)
				{
					ld_calc_amount += Convert.ToDecimal(ConversionUtil.RemoveComma(GridView1.Rows[i].Cells[6].Text));
				}

				GridView1.FooterRow.Cells[6].Text = ConversionUtil.AddComma(ld_calc_amount.ToString());
			}			
		}

		#endregion

	}
}
